//
//  LeftMenuController.swift
//  Order
//
//  Created by Lazyloading on 2020/7/7.
//  Copyright © 2020 lazyloading. All rights reserved.
//

import UIKit
import SnapKit
import PKHUD
import LEEAlert

let kLeftMenuCellID = "kLeftMenuCellID";

/// 侧滑菜单
class LeftMenuController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
    
    lazy var tableView : UITableView = {
        let table = UITableView.init(frame: self.view.bounds,style: .grouped);
        
        table.backgroundColor = ZMColor.Gray.gray1;
        table.delegate = self;
        table.dataSource = self;
        table.register(UITableViewCell.self, forCellReuseIdentifier: kLeftMenuCellID);
        table.showsVerticalScrollIndicator = false;
        table.separatorStyle = .none;
        
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = false;
        };
        return table;
        
    }();
    
    lazy var head: LeftMenuHeadView = {
        let view = LeftMenuHeadView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: NavBar_H+40));
        view.backgroundColor = ZMColor.Orange.orange1;
        weak var weakSelf = self;
        view.rechargeBlock = { button in
            let navi = weakSelf!.menuContainerViewController.centerViewController!;
            weakSelf!.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            let vc = RechargeController();
            vc.finishBlock = { controller in
                weakSelf?.getUserinfo();
            };
            
            (navi as! UINavigationController).pushViewController(vc, animated: true);
        }
        return view;
    }();
    
    lazy var dataArray : [[[String : String]]] = {
        var temp = Array<[[String : String]]>();
        
        let section1 = [
            [
                "type" : "0",
                "title" : "收款二维码"
            ],
            [
                "type" : "1",
                "title" : "收款银行卡"
            ]
        ];
        
        let section2 = [
            [
                "type" : "2",
                "title" : "历史抢单"
            ]
        ];
        
        let section3 = [
            [
                "type" : "3",
                "title" : "最新活动"
            ]
        ];
        
        let section4 = [
            [
                "type" : "4",
                "title" : "邀请有奖"
            ],
            [
                "type" : "5",
                "title" : "补贴报表"
            ],
            [
                "type" : "6",
                "title" : "我的团队"
            ],
            [
                "type" : "8",
                "title" : "查看公告"
            ],
            [
                "type" : "9",
                "title" : "联系客服"
            ],
            [
                "type" : "10",
                "title" : "邀请码"
            ]
        ];
        
        let section5 = [
            [
                "type" : "7",
                "title" : "退出登录"
            ]
        ];
        
        temp = [section1,section2,section3,section4,section5];
        
        return temp
        
    }();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loadDefaultSetting();
        self.initSubViews();
        
        self.menuContainerViewController
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.getUserinfo();
    }
    // MARK: 👉🏻 🐷Life cycle🐷
    // MARK: 👉🏻 🐷UITableView Delegate🐷
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArray.count;
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray[section].count;
     }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60;
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10;
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0;
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView();
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView();
    }
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dict = self.dataArray[indexPath.section][indexPath.row];
        let cell =  tableView.dequeueReusableCell(withIdentifier: kLeftMenuCellID);
        
        let type = dict["type"];
        
        cell?.textLabel?.text = dict["title"];
        cell?.textLabel?.font = UIFont.init(fontType: .regular, fontSize: 15);
        if type?.int() == 7 {
            cell?.accessoryType = .none;
            cell?.textLabel?.textColor = .red;
            cell?.textLabel?.textAlignment = .center;
        }else{
            cell?.textLabel?.textAlignment = .left;
            cell?.textLabel?.textColor = ZMColor.Black.black1;
            cell?.accessoryType = .disclosureIndicator;
        }
        
        return cell!;
     }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);
        
        let navi = self.menuContainerViewController.centerViewController!;
        if ((navi.isKind(of: UINavigationController.self)) == false){
            return;
        }
        
        ZMLog("点击\(indexPath.row)");
        let dict = self.dataArray[indexPath.section][indexPath.row];
        guard let type = dict["type"] else { return  };
        
        switch Int(type) {
            
        case 0:
            
            self.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            (navi as! UINavigationController).pushViewController(QRCodeListController(), animated: true);
            
            break;
            
        case 1:
            
            self.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            (navi as! UINavigationController).pushViewController(BankListViewController(), animated: true);
            
            break
            
        case 2:
            
            self.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            (navi as! UINavigationController).pushViewController(HistoryOrderController(), animated: true);
            
            break
            
        case 7:
            UserDefaults.standard.removeObject(forKey: kUserInfo);
            self.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            UIApplication.shared.delegate?.window??.rootViewController = BaseNavigationController.init(rootViewController: LoginController());

            break;
            
        case 8:
            self.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            (navi as! UINavigationController).pushViewController(NoticeController(), animated: true);
            break;
            
        case 9:
            self.menuContainerViewController.setSideMenuState(state: .closed, completeBlock: nil)
            (navi as! UINavigationController).pushViewController(CustomerController(), animated: true);
            break;
            
        case 10:
            self.inviteCodeRequest();
            break;
            
        default:
            HUD.flash(.label("系统升级中，敬请期待"), delay: 1);
        
            break

        }
        
    }

    // MARK: 👉🏻 🐷Custom Delegate🐷
    // MARK: 👉🏻 🐷Event  Response🐷
    // MARK: 👉🏻 🐷Private Methods🐷
    func getUserinfo(){
        
        weak var weakSelf = self;
        MoyaRequest(.userInfo, success: { (response : BaseResponse<[String : Any]>) in
            if response.respCode == 200{
                weakSelf?.head.moneyLabel.text = "￥\(response.data!["balance"] ?? "0.00")"
            }else{
                
            }
        }) { (error) in
            
        }
    }
    //获取邀请码
    func inviteCodeRequest()  {
        weak var weakSelf = self;
        MoyaRequest(.inviteCode, success: { (response : BaseResponse<[String:Any]>) in
            if response.respCode == 200{
                let code = "\(response.data!["inviteCode"] ?? "")";
                weakSelf?.inviteCodeAlert(code: code);
            }else{
                
            }
        }) { (error) in
            
        }
        
    }
    //邀请码弹窗
    func inviteCodeAlert(code : String)  {
        let alertW = KWIDTH - 100;
        let alertH = 190;
        let notice = InviteCodeView.init(frame: CGRect.init(x: 0, y: 0, width: Int(alertW), height: alertH));
        notice.inviteCodeLabel.text = code;
        
        let alert = LEEAlert.alert()
        _ = alert.config.leeCustomView(notice)
            .leeHeaderInsets(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
            .leeMaxWidth(alertW)
            .leeMaxHeight(CGFloat(alertH))
            .leeClickBackgroundClose(true)
            .leeShow();
        
        notice.copyBlock = {button in
            LEEAlert.close(completionBlock: nil);
        }
    }
    // MARK: 👉🏻 🐷Lazy loading🐷
    // MARK: 👉🏻 🐷Init SubViews🐷
    func loadDefaultSetting()  {
        self.view.backgroundColor = .white;
    }
    
    func initSubViews()  {
        
        self.tableView.tableHeaderView = self.head;
        
        self.view.addSubview(self.tableView);
        
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
        
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews();
        self.getUserinfo();
    }

}
